<template>
  <div id="detail">
    <detail-headers class="detail-nav">
      <div slot="left" class="to" @click="backOff">
        <i class="iconfont icon-zuo"></i>
      </div>
      <div
        slot="conter"
        v-for="(item, index) in title"
        :key="index"
        class="title"
        :class="{ active: currentIndex === index }"
        @click="titleToggle(index)"
      >
        {{ item }}
      </div>
      <div slot="right" class="cart" @click="skipCart">
        <i class="iconfont icon-che-copy"></i>
      </div>
    </detail-headers>

    <detail-scroll
      class="content"
      @scroll="contentScroll"
      :pull-up-load="true"
      :probe-type="3"
      ref="scroll"
    >
      <detail-swiper class="swiperImage">
        <detail-swiper-item
          v-for="(item, index) in swiperImageList"
          :key="index"
        >
          <img :src="item" alt="" />
        </detail-swiper-item>
      </detail-swiper>

      <div class="detail-info">
        <div class="title">{{ goods.title }}</div>
        <div class="price">
          <p>{{ goods.price }}</p>
          <del>{{ goods.oldPrice }}</del>
          <span>{{ goods.discount }}</span>
        </div>
        <div class="sales" v-if="goods.columns">
          <span>{{ goods.columns[0] }}</span>
          <span>{{ goods.columns[1] }}</span>
          <span>{{ goods.services[goods.services.length - 1].name }}</span>
        </div>
        <template v-if="goods.services">
          <div class="services">
            <div v-for="(item, index) in goodsLength" :key="index">
              <img :src="item.icon" alt="" />
              <span>{{ item.name }}</span>
            </div>
          </div>
        </template>
      </div>

      <detail-shop-info :shopInfo="shop"></detail-shop-info>

      <div class="image-info" v-if="imageList.detailImage">
        <div class="title">
          <div class="start"></div>
          <div class="conter">{{ imageList.desc }}</div>
          <div class="end"></div>
        </div>
        <p class="text">{{ imageList.detailImage[0].key }}</p>
        <div class="list">
          <ul>
            <li
              v-for="(item, index) in imageList.detailImage[0].list"
              :key="index"
            >
              <img :src="item" alt="" @load="imagesLoad" />
            </li>
          </ul>
        </div>
      </div>

      <detail-goods-params
        :goods-params="goodsInfoParams"
        ref="params"
      ></detail-goods-params>

      <detail-comment :comment="commentInfo" ref="comment"></detail-comment>

      <div class="recommend">
        <span>热门推荐</span>
        <detail-goods-list
          :goods-list="recommendList"
          ref="recommend"
        ></detail-goods-list>
      </div>
    </detail-scroll>

    <detail-soll-top v-show="isShowSollTop" @click.native="pageSollTop">
    </detail-soll-top>

    <detail-bottom-bar @addToCart="addToCart"></detail-bottom-bar>
  </div>
</template>

<script>
import DetailHeaders from '../../components/content/Headers'
import DetailSwiper from '../../components/common/swiper/Swiper'
import DetailSwiperItem from '../../components/common/swiper/SwiperItem'
import DetailShopInfo from './child/ShopInfo'
import DetailScroll from '../../components/common/Scroll/Scroll'
import DetailGoodsParams from './child/GoodsParams'
import DetailGoodsList from '../../components/content/GoodsList'
import DetailComment from './child/Comment'
import DetailSollTop from '../../components/content/SollTop'
import DetailBottomBar from './child/BottomBar'

import { getDetail, getRecommend } from '../../network/getData'
import { Goods, Shop, GoodsParams } from '../../network/detail'
import { debounce } from '../../network/utils'

export default {
  name: 'Detail',
  data() {
    return {
      title: ['商品', '参数', '评论', '推荐'], // nav
      swiperImageList: [], // 轮播图图片
      goods: {}, // 商品信息
      shop: {}, // 店铺信息
      imageList: {}, // 商品图片信息
      count: 0, // 不让图片加载多次
      goodsInfoParams: {}, // 商品详细参数
      recommendList: [], // 商品热门
      commentInfo: {}, // 评论信息
      isShowSollTop: false, // 是否显示回到顶部按钮
      currentIndex: 0, // 当前样式
      themePositionY: [], // 组件的头部坐标
      debounceFun: null // 存储函数
    }
  },
  components: {
    DetailHeaders,
    DetailSwiper,
    DetailSwiperItem,
    DetailShopInfo,
    DetailScroll,
    DetailGoodsParams,
    DetailGoodsList,
    DetailComment,
    DetailSollTop,
    DetailBottomBar
  },
  created() {
    this._getDetail()
    this._getRecommend()
  },
  mounted() {
    const refresh = debounce(this.$refs.scroll.refresh, 200)
    const thenme = debounce(this.getThemeFun, 100)
    this.$bus.$on('itemImageLoad', () => {
      refresh()
      thenme()
    })
  },
  // 离开之后销毁图片加载事件
  destroyed() {
    // this.$bus.$off('itemImageLoad', this.debounceFun)
  },
  methods: {
    // 获取商品信息
    _getDetail() {
      const id = window.sessionStorage.getItem('id')
      getDetail(id).then((res) => {
        this.swiperImageList = res.result.itemInfo.topImages

        // 获取用得到的数据
        this.goods = new Goods(
          res.result.itemInfo,
          res.result.columns,
          res.result.shopInfo.services
        )
        this.shop = new Shop(res.result.shopInfo)
        this.goodsInfoParams = new GoodsParams(
          res.result.itemParams.info,
          res.result.itemParams.rule
        )
        this.imageList = res.result.detailInfo

        if (res.result.rate.cRate > 0) {
          this.commentInfo = res.result.rate.list[0]
        }
      })
    },
    // 获取热门推荐
    _getRecommend() {
      getRecommend().then((res) => {
        this.recommendList = res.data.list
      })
    },
    // 后退
    backOff() {
      this.$router.go(-1)
    },
    // 监听图片加载完成事件
    imagesLoad() {
      if (++this.count === this.imageList.detailImage[0].list.length) {
        this.$refs.scroll.refresh()
        // 再次获取坐标
        this.getThemeFun()
      }
    },
    // 回到顶部
    pageSollTop() {
      this.$refs.scroll.scrollTo(0, 0, 500)
    },
    // 是否显示回到顶部按钮
    contentScroll(position) {
      const y = -position.y

      if (y >= 1000) {
        this.isShowSollTop = true
      } else {
        this.isShowSollTop = false
      }

      // 对应的选项卡高亮
      const index = this.themePositionY.findIndex((item, index) => {
        return y >= item && y < this.themePositionY[index + 1]
      })
      this.currentIndex = index
    },
    // 滚动到对应的位置
    titleToggle(index) {
      this.currentIndex = index
      this.$refs.scroll.scrollTo(0, -this.themePositionY[index], 200)
    },
    // 获取组件的坐标
    getThemeFun() {
      if (!this.$refs.params) {
        return
      }
      this.themePositionY = []
      this.themePositionY.push(0)
      this.themePositionY.push(this.$refs.params.$el.offsetTop - 45)
      this.themePositionY.push(this.$refs.comment.$el.offsetTop - 45)
      this.themePositionY.push(this.$refs.recommend.$el.offsetTop - 80)
      this.themePositionY.push(Infinity)
    },
    // 添加购物车
    addToCart() {
      const obj = {}
      obj.iid = window.sessionStorage.getItem('id')
      obj.image = this.swiperImageList[0]
      obj.title = this.goods.title
      obj.desc = this.goods.desc
      obj.count = 0
      obj.name = this.shop.name
      obj.checked = false
      obj.newPrice = this.goods.nowPrice

      this.$store.dispatch('addCart', obj)
    },
    // 跳转到购物车
    skipCart() {
      this.$router.push('/cart')
    }
  },
  computed: {
    // 截取数组
    goodsLength() {
      let goodslength = this.goods.services
      if (goodslength.length >= 5) {
        goodslength = goodslength.slice(1, 4)
      }
      return goodslength
    }
  }
}
</script>

<style lang="less" scoped>
#detail {
  height: 100vh;
  overflow: hidden;
}

.active {
  color: var(--color-a);
}

.content {
  height: calc(100% - 90px);
}

.detail-nav {
  background-color: #fff;
  font-weight: normal;
  color: var(--color-text);
  .to {
    margin-left: 10px;
    margin-top: 2px;
  }
  .title {
    display: inline;
    font-size: 14px;
    margin: 0 10px;
    text-align: center;
  }
  .cart {
    text-align: center;
    i {
      font-size: 20px;
    }
  }
}

.swiperImage {
  height: 300px;
}

.active {
  color: var(--color-a);
}

.detail-info {
  padding: 10px;
  .title {
    color: #333;
  }
  .price {
    display: flex;
    padding: 10px 0;
    p {
      font-size: 24px;
      color: var(--color-a);
    }
    del {
      color: #999;
      font-size: 14px;
      align-self: flex-end;
      margin: 0 5px;
    }
    span {
      font-size: 12px;
      height: 18px;
      line-height: 18px;
      padding: 0 5px;
      background-color: var(--color-a);
      border-radius: 8px;
      color: #fff;
    }
  }
  .sales {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    color: #999;
    border-bottom: 1px solid #ccc;
    padding-bottom: 10px;
  }
  .services {
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    padding: 15px 0 5px;
    div {
      display: flex;
      align-items: center;
    }
    img {
      width: 14px;
      height: 14px;
    }
  }
}

.title .start,
.title .end {
  position: relative;
  width: 90px;
  height: 1px;
  background-color: #000;
}

.title .start::before {
  content: '';
  position: absolute;
  top: -4px;
  left: 0;
  width: 5px;
  height: 5px;
  background-color: #000;
}

.title .end {
  right: -245px;
  bottom: 0;
}

.title .end::after {
  content: '';
  position: absolute;
  top: -4px;
  right: 0;
  width: 5px;
  height: 5px;
  background-color: #000;
}

.image-info {
  .title {
    padding: 20px;
    position: relative;
    .conter {
      padding: 10px 0;
      font-size: 14px;
    }
  }
  .text {
    padding: 0 10px 10px;
  }
  .list {
    img {
      width: 100%;
    }
  }
}

.recommend {
  border-top: 8px solid #f2f5f8;
  padding-top: 10px;
  span {
    margin-left: 10px;
    font-size: 15px;
  }
}
</style>
